//
//  LSTestViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/7/26.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSTestViewController.h"
#import "LSTestTableViewCell.h"
#import "LSTestSelectCell.h"
#import "LSTestSelectModel.h"
#import "LSTestSelcetNewCell.h"
@interface LSTestViewController () <UITableViewDataSource, UITableViewDelegate, LSTestSelectCellDelegate>
@property (nonatomic, strong) UITableView *selectTableView;
@property (nonatomic, strong) NSMutableArray <LSTestSelectModel *> *displayDataArrayM;

@property (nonatomic, strong) NSMutableArray *tempArrayMOne;
@property (nonatomic, strong) NSMutableArray *tempArrayMTwo;
@property (nonatomic, strong) NSMutableArray *tempArrayMThree;
@property (nonatomic, strong) NSMutableArray *tempArrayMFour;
@property (nonatomic, strong) NSMutableArray *tempArrayMFive;
@property (nonatomic, strong) NSMutableArray *tempArrayMSix;

@end

static NSString *LSTestSelectCellID = @"LSTestSelectCellID";
static NSString *LSTestTableViewCellID = @"LSTestTableViewCellID";

@implementation LSTestViewController
- (NSMutableArray<LSTestSelectModel *> *)selectedModelArray{
    if (!_selectedModelArray) {
        _selectedModelArray = [NSMutableArray array];
    }
    return _selectedModelArray;
}
-(instancetype)init{
    self=[super init];
    if (self) {
        self.providesPresentationContextTransitionStyle = NO;
        self.definesPresentationContext = YES;
        self.modalPresentationStyle = UIModalPresentationOverFullScreen;
        self.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = hexColorAlpha(000000, 0.0f);
    UIButton *backgroundButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    backgroundButton.backgroundColor = hexColorAlpha(000000, 0.2f);
    [backgroundButton addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backgroundButton];
    [self.view addSubview:self.selectTableView];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:true completion:nil];
}

- (void)setDataModelArrayM:(NSMutableArray *)dataModelArrayM {
    for (NSInteger i = 0; i < dataModelArrayM.count; i++) {
        LSTestSelectModel *model = dataModelArrayM[i];
       for (LSTestSelectModel *selectModel in self.selectedModelArray) {
            if ([selectModel.id isEqualToString:model.id]) {
                model.isSelected = YES;
                [dataModelArrayM replaceObjectAtIndex:i withObject:model];
                break;
            }
        }
    }
    _dataModelArrayM = dataModelArrayM;
    self.displayDataArrayM = dataModelArrayM.mutableCopy;
    NSMutableArray *displayDataArrayMcopy = self.displayDataArrayM.mutableCopy;
    for (LSTestSelectModel *model in displayDataArrayMcopy) {
        if (model.isOpen) {
            NSInteger index = [displayDataArrayMcopy indexOfObject:model];
            [self insertMultipulLevelModelsWithModel:model fromIndex:index];
        }
    }
    [self rearrangeSelectTableViewFrame];
    [self.selectTableView reloadData];
}

- (void)rearrangeSelectTableViewFrame {
    CGFloat maxHeight = ScreenHeight-(SafeAreaTopHeight-40)-SafeAreaBottomHeight-100;
    CGRect oldFrame = self.selectTableView.frame;
    CGFloat newHeight = 40*self.displayDataArrayM.count+50+50+30;
    if (newHeight > maxHeight) {
        newHeight = maxHeight;
    }
    self.selectTableView.frame = CGRectMake(25, oldFrame.origin.y, ScreenWidth-50, newHeight);
    [UIView animateWithDuration:0.25 animations:^{
        self.selectTableView.frame = CGRectMake(25, (ScreenHeight-(SafeAreaTopHeight-64-SafeAreaBottomHeight)-newHeight)/2, ScreenWidth-50, newHeight);
    }];
}

//- (void)arrangeArray:(NSMutableArray *)arrM With:(NSMutableArray *)arrMLast withLevel:(NSInteger)level {
//    NSMutableArray *arrMLastM = arrMLast.mutableCopy;
//    if (level == 1) {
//        self.tempArrayMOne = arrM.mutableCopy;
////        if (arrMLast.count > 0) [self arrangeArray:self.dataArrayM With:arrMLast withLevel:2];
//    } else if (level == 2) {
//        for (LSTestSelectModel *model in self.tempArrayMOne) {
//            for (LSTestSelectModel *model2 in arrMLastM) {
//                if ([model2.pid isEqualToString:model.id]) {
//                    model2.level = 2;
//                    [model.bottomDataArrayM addObject:model2];
//                    [self.tempArrayMTwo addObject:model2];
//                    [arrMLast removeObject:model2];
//                }
//            }
//        }
//        if (arrMLast.count > 0) [self arrangeArray:self.dataArrayM With:arrMLast withLevel:3];
//    } else if (level == 3) {
//        for (LSTestSelectModel *model in self.tempArrayMTwo) {
//            for (LSTestSelectModel *model2 in arrMLastM) {
//                if ([model2.pid isEqualToString:model.id]) {
//                    model2.level = 3;
//                    [model.bottomDataArrayM addObject:model2];
//                    [self.tempArrayMThree addObject:model2];
//                    [arrMLast removeObject:model2];
//                }
//            }
//        }
//        if (arrMLast.count > 0) [self arrangeArray:self.dataArrayM With:arrMLast withLevel:4];
//    } else if (level == 4) {
//        for (LSTestSelectModel *model in self.tempArrayMThree) {
//            for (LSTestSelectModel *model2 in arrMLastM) {
//                if ([model2.pid isEqualToString:model.id]) {
//                    model2.level = 4;
//                    [model.bottomDataArrayM addObject:model2];
//                    [self.tempArrayMFour addObject:model2];
//                    [arrMLast removeObject:model2];
//                }
//            }
//        }
//        if (arrMLast.count > 0) [self arrangeArray:self.dataArrayM With:arrMLast withLevel:5];
//    } else if (level == 5) {
//        for (LSTestSelectModel *model in self.tempArrayMFour) {
//            for (LSTestSelectModel *model2 in arrMLastM) {
//                if ([model2.pid isEqualToString:model.id]) {
//                    model2.level = 5;
//                    [model.bottomDataArrayM addObject:model2];
//                    [self.tempArrayMFive addObject:model2];
//                    [arrMLast removeObject:model2];
//                }
//            }
//        }
//        if (arrMLast.count > 0) [self arrangeArray:self.dataArrayM With:arrMLast withLevel:6];
//    } else if (level == 6) {
//        for (LSTestSelectModel *model in self.tempArrayMFive) {
//            for (LSTestSelectModel *model2 in arrMLastM) {
//                if ([model2.pid isEqualToString:model.id]) {
//                    model2.level = 6;
//                    [model.bottomDataArrayM addObject:model2];
//                    [self.tempArrayMSix addObject:model2];
//                    [arrMLast removeObject:model2];
//                }
//            }
//        }
//    } else {
//        // do nothing
//    }
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.displayDataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSTestSelectModel *model = self.displayDataArrayM[indexPath.row];
    LSTestSelcetNewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSTestSelcetNewCell"];
    if (!cell) {
        cell =[[[NSBundle mainBundle]loadNibNamed:@"LSTestSelcetNewCell" owner:nil options:nil]lastObject];
    }
    cell.moreImageView.transform = CGAffineTransformMakeRotation(-(M_PI / 2));
    cell.moreImageView.hidden = YES;
    if (!model.isLeaf) {
        cell.moreImageView.hidden = NO;
        if (model.bottomDataArrayM.count > 0) {
               if (model.isOpen) {
                   cell.moreImageView.transform = CGAffineTransformIdentity;
               } else {
                   cell.moreImageView.transform = CGAffineTransformMakeRotation(-(M_PI / 2));
               }
           }
    }else{
        if (model.isParent) {
           cell.moreImageView.hidden = NO;
            if (model.isOpen) {
              cell.moreImageView.transform = CGAffineTransformIdentity;
          } else {
              cell.moreImageView.transform = CGAffineTransformMakeRotation(-(M_PI / 2));
          }
        }else{
            cell.moreImageView.hidden = YES;
        }
       
    }
   
    WS
    cell.callBackWithSelectedobject = ^{
        model.isSelected = !model.isSelected;
        [weakSelf.displayDataArrayM replaceObjectAtIndex:indexPath.row withObject:model];
        if (model.isSelected) {
            [weakSelf.selectedModelArray addObject:model];
        }else{
            for (LSTestSelectModel *selectModel in weakSelf.selectedModelArray) {
                if ([model.id isEqualToString:selectModel.id]) {
                    [weakSelf.selectedModelArray removeObject:selectModel];
                    break;
                }
            }
            
        }
        [weakSelf.selectTableView reloadData];
    };
    cell.nameLabel.text = model.name;
    cell.buttonLeadMargin.constant = (model.level-1)*15;
    if (model.isSelected) {
        cell.selectBtn.selected = YES;
    }else{
        cell.selectBtn.selected = NO;
    }
    return cell;
}
- (void)copyToDepartmentWihtModel:(LSTestSelectModel*)model withIndex:(NSInteger)index{
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:[NSString stringWithFormat:@"%@&token=%@",getSendList,[UserInfoModel sharedInstance].token] param:@{@"parentid":model.id} completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSNumber *status = responseObject[@"status"];
            if (status.intValue == 200) {
                NSArray *array = responseObject[@"data"];
                if (array && array.count>0) {
                    NSMutableArray *tempArray = [NSMutableArray array];
                    for (NSInteger i = 0; i < array.count; i++) {
                        NSMutableDictionary *dict = [array[i] mutableCopy];
                         LSTestSelectModel *tempModel = [[LSTestSelectModel alloc]init];
                        tempModel.isOpen = false;
                          tempModel.bottomDataArrayM = [[NSMutableArray alloc] init];
                          tempModel.name = dict[@"name"];;//初始都为最高级
                          tempModel.id = dict[@"id"];
                          tempModel.pid = dict[@"pid"];
                          tempModel.code = dict[@"code"];
                        tempModel.isLeaf = [dict[@"isLeaf"] boolValue];
                          tempModel.level = model.level+1;
                        for (NSInteger i = 0; i < self.selectedModelArray.count; i++) {
                            LSTestSelectModel *model = self.selectedModelArray[i];
                            if ([model.id isEqualToString:tempModel.id]) {
                               tempModel.isSelected = YES;
//                                [self.selectedModelArray replaceObjectAtIndex:i withObject:tempModel];
                               break;
                           }
                        }
                       
                         if (tempModel) [tempArray addObject:tempModel];
                   }
                     model.bottomDataArrayM = tempArray;
                    [self insertMultipulLevelModelsWithModel:model fromIndex:index];
                  model.isOpen = true;
                  [self rearrangeSelectTableViewFrame];
                }
                [self.selectTableView reloadData];
        }
    }
     }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSTestSelectModel *model = self.displayDataArrayM[indexPath.row];
    if (model.isOpen) {
       [self removeMultipulLevelModelsWithModel:model];
        model.isOpen = false;
        [self rearrangeSelectTableViewFrame];
        [self.selectTableView reloadData];
    }else{
        if (model.bottomDataArrayM.count>0) {
            [self insertMultipulLevelModelsWithModel:model fromIndex:indexPath.row];
             model.isOpen = true;
             [self rearrangeSelectTableViewFrame];
            [self.selectTableView reloadData];
        }else{
            if (!model.isLeaf) {
                [self copyToDepartmentWihtModel:model withIndex:indexPath.row];
            }
        }
    }
   
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (void)removeMultipulLevelModelsWithModel:(LSTestSelectModel *)model {
    for (LSTestSelectModel *subModel in model.bottomDataArrayM) {
        if (subModel.isOpen) {
            [self removeMultipulLevelModelsWithModel:subModel];
        }
        [self.displayDataArrayM removeObject:subModel];
    }
}

- (NSInteger)insertMultipulLevelModelsWithModel:(LSTestSelectModel *)model fromIndex:(NSInteger)index {
    for (LSTestSelectModel *subModel in model.bottomDataArrayM) {
        [self.displayDataArrayM insertObject:subModel atIndex:index + 1];
        index += 1;
        if (subModel.isOpen) {
            index = [self insertMultipulLevelModelsWithModel:subModel fromIndex:index];
        }
    }
    return index;
}

#pragma mark - LSTestSelectCellDelegate
- (void)didSelectTestSelectCellWithModel:(LSTestSelectModel *)model {
   
}

- (UITableView *)selectTableView {
    if (!_selectTableView) {
        _selectTableView = [[UITableView alloc] initWithFrame:CGRectMake(25, 100+(SafeAreaTopHeight-64), ScreenWidth-50, ScreenHeight-(SafeAreaTopHeight-64)-200-SafeAreaBottomHeight)];
        _selectTableView.backgroundColor = UIColor.whiteColor;
        _selectTableView.layer.cornerRadius = 5;
        _selectTableView.layer.masksToBounds = true;
        _selectTableView.delegate = self;
        _selectTableView.dataSource = self;
        _selectTableView.tableFooterView = [UIView new];
        [_selectTableView registerClass:LSTestSelectCell.class forCellReuseIdentifier:LSTestSelectCellID];
        [_selectTableView registerClass:LSTestTableViewCell.class forCellReuseIdentifier:LSTestTableViewCellID];
        UILabel *tableViewHeaderView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _selectTableView.frame.size.width, 50) andText:@"请选择" andTextColor:hexColor(333333) andFont:[UIFont systemFontOfSize:16] andTextAlignment:NSTextAlignmentCenter];
        _selectTableView.tableHeaderView = tableViewHeaderView;
        
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _selectTableView.frame.size.width, 50+30)];
        _selectTableView.tableFooterView = footView;
        UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        cancleBtn.clipsToBounds = YES;
        cancleBtn.layer.cornerRadius = 3;
        cancleBtn.frame = CGRectMake(20, 10+20, (footView.frame.size.width - 20*3)/2.0, 30);
        cancleBtn.layer.borderColor = hexColor(666666).CGColor;
        [cancleBtn setTitleColor:hexColor(333333) forState:UIControlStateNormal];
        cancleBtn.layer.borderWidth = 1.0;
        cancleBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [cancleBtn addTarget:self action:@selector(cancelBtnClickd) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:cancleBtn];
        
        UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
       [finishBtn setTitle:@"确定" forState:UIControlStateNormal];
       finishBtn.clipsToBounds = YES;
       finishBtn.layer.cornerRadius = 3;
       finishBtn.frame = CGRectMake(footView.frame.size.width/2.0+10, 10+20, (footView.frame.size.width - 20*3)/2.0, 30);
       finishBtn.layer.borderColor = NAV_COLOR.CGColor;
       finishBtn.layer.borderWidth = 1.0;
    finishBtn.backgroundColor = NAV_COLOR;
        finishBtn.titleLabel.font = [UIFont systemFontOfSize:15];
       [finishBtn addTarget:self action:@selector(finishBtnClicked) forControlEvents:UIControlEventTouchUpInside];
       [footView addSubview:finishBtn];
        
    }
    return _selectTableView;
}
- (void)cancelBtnClickd{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)finishBtnClicked{
     if (self.didSelectAreaModelBlock) {
           self.didSelectAreaModelBlock(self.selectedModelArray);
           [self dismissViewControllerAnimated:true completion:nil];
       }
}
- (NSMutableArray<LSTestSelectModel *> *)displayDataArrayM {
    if (!_displayDataArrayM) {
        _displayDataArrayM = [[NSMutableArray alloc] init];
    }
    return _displayDataArrayM;
}

- (NSMutableArray *)tempArrayMOne {
    if (!_tempArrayMOne) {
        _tempArrayMOne = [[NSMutableArray alloc] init];
    }
    return _tempArrayMOne;
}

- (NSMutableArray *)tempArrayMTwo {
    if (!_tempArrayMTwo) {
        _tempArrayMTwo = [[NSMutableArray alloc] init];
    }
    return _tempArrayMTwo;
}

- (NSMutableArray *)tempArrayMThree {
    if (!_tempArrayMThree) {
        _tempArrayMThree = [[NSMutableArray alloc] init];
    }
    return _tempArrayMThree;
}

- (NSMutableArray *)tempArrayMFour {
    if (!_tempArrayMFour) {
        _tempArrayMFour = [[NSMutableArray alloc] init];
    }
    return _tempArrayMFour;
}

- (NSMutableArray *)tempArrayMFive {
    if (!_tempArrayMFive) {
        _tempArrayMFive = [[NSMutableArray alloc] init];
    }
    return _tempArrayMFive;
}

- (NSMutableArray *)tempArrayMSix {
    if (!_tempArrayMSix) {
        _tempArrayMSix = [[NSMutableArray alloc] init];
    }
    return _tempArrayMSix;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
